/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.web.member;

import com.server.common.config.Global;
import com.server.common.persistence.Page;
import com.server.common.utils.IPUtils;
import com.server.common.utils.MD5Utils;
import com.server.common.utils.StringUtils;
import com.server.common.utils.UUIDUtils;
import com.server.common.web.BaseController;
import com.server.modules.api.service.IMService;
import com.server.modules.sys.entity.Dict;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.bank.Bank;
import com.server.modules.sys.entity.businessrecord.TBusinessRecord;
import com.server.modules.sys.entity.friends.Friends;
import com.server.modules.sys.entity.loan.Loan;
import com.server.modules.sys.entity.loan.LoanMaterialtypeRe;
import com.server.modules.sys.entity.loan.LoanType;
import com.server.modules.sys.entity.material.MaterialType;
import com.server.modules.sys.entity.material.MaterialUpload;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.entity.member.MemberBankcard;
import com.server.modules.sys.entity.servicerecord.ServiceRecord;
import com.server.modules.sys.service.DictService;
import com.server.modules.sys.service.SystemService;
import com.server.modules.sys.service.UserService;
import com.server.modules.sys.service.bank.BankService;
import com.server.modules.sys.service.businessrecord.TBusinessRecordService;
import com.server.modules.sys.service.friends.FriendsService;
import com.server.modules.sys.service.loan.CustomPayService;
import com.server.modules.sys.service.loan.LoanMaterialtypeReService;
import com.server.modules.sys.service.loan.LoanService;
import com.server.modules.sys.service.loan.LoanTypeService;
import com.server.modules.sys.service.material.MaterialTypeService;
import com.server.modules.sys.service.material.MaterialUploadService;
import com.server.modules.sys.service.member.MemberBankcardService;
import com.server.modules.sys.service.member.MemberService;
import com.server.modules.sys.service.servicerecord.ServiceRecordService;
import com.server.modules.sys.utils.CollectionGroupUtils;
import com.server.modules.sys.utils.WordUtils;
import com.server.modules.sys.utils.date.DateUtil;
import com.server.modules.sys.vo.web.MemberMaterial;
import com.server.modules.sys.vo.web.MemberMaterialUpload;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 普通用户信息Controller
 * @author 颜洪毅/傅友园
 * @version 2016-10-11
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/member/member")
public class MemberController extends BaseController {
	@Resource
    protected IMService imService;

	@Autowired
	private MemberService memberService;
	
	@Autowired
	private ServiceRecordService serviceRecordService;

	@Autowired
	private TBusinessRecordService businessRecordService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private MaterialTypeService materialTypeService;

	@Autowired
	private DictService dictservice;

	@Autowired
	private LoanTypeService loanTypeService;

	@Autowired
	private LoanService loanService;
	@Autowired
	private LoanMaterialtypeReService loanMaterialtypeReService;

	@Autowired
	private MaterialUploadService materialUploadService;

	@Autowired
	private MemberBankcardService memberBankcardService;

	@Autowired
	private DictService dictService;


	@Autowired
	private BankService bankService;


	@Autowired
	private CustomPayService customPayService;

	@Autowired
	private UserService userService;

	@Autowired
	private FriendsService friendsService;


	@ModelAttribute
	public Member get(@RequestParam(required=false) String id) {
		Member entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = memberService.get(id);
		}
		if (entity == null){
			entity = new Member();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:member:member:view")
	@RequestMapping(value = {"list", ""})
	public String list(Member member, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Member> page = memberService.findPage(new Page<Member>(request, response), member); 
		model.addAttribute("page", page);
		model.addAttribute("member", member);
		model.addAttribute("nams",memberService.findList(new Member()));
		return "modules/sys/member/memberList";
	}

	@RequiresPermissions("sys:member:member:tel")
	@RequestMapping(value = "tel")
	public String tel(Member member,HttpServletRequest request, HttpServletResponse response,Model model){
		Page<Member> page = memberService.telList(new Page<Member>(request, response),member);
		model.addAttribute("page",page);
		model.addAttribute("member",member);
		return "modules/sys/member/telmemberList";
	}

	@RequiresPermissions("sys:member:member:memberloan")
	@RequestMapping(value = "memberloan")
	public String memberloan(Member member,Loan loan,HttpServletRequest request, HttpServletResponse response,Model model){
		model.addAttribute("banks",bankService.findList(new Bank()));
		model.addAttribute("bankName",loan.getBankName());
		model.addAttribute("bankId",loan.getBankId());
		model.addAttribute("loanId",member.getLoanId());
		if(StringUtils.isBlank(member.getLoanId())){
			Page<Member> page =new Page<>();
			model.addAttribute("page",page);
			model.addAttribute("member",member);
		}else{
			Page<Member> page = memberService.memberloan(new Page<Member>(request, response),member);
			model.addAttribute("page",page);
			model.addAttribute("member",member);
		}

		return "modules/sys/member/memberLoan";
	}

	@RequiresPermissions("sys:member:member:view")
	@RequestMapping(value = "form")
	public String form(Member member, Model model) {
		model.addAttribute("member", member);
		return "modules/sys/member/memberForm";
	}
	/**
	 * 结算页
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:member:member:view")
	@RequestMapping(value = "load/viewMemberInfoPage")
	public String viewMemberInfoPage(Member member, Model model) {
		model.addAttribute("member",member);
		String memberId=member.getId();
		//查询用户上传的资料
		if(StringUtils.isNotBlank(memberId)/*&&StringUtils.isNotBlank(materialTypeId)*/){
			MaterialUpload query=new MaterialUpload();
			//    query.setTypeId(materialTypeId);
			query.setMemberId(memberId);
			List<MaterialUpload> list = materialUploadService.findList(query);
			Map<String,List<MaterialUpload>> mapTemp=new HashMap<>();
			//给上传资料分组
			for (MaterialUpload materialUpload : list) {
				if(!mapTemp.containsKey(materialUpload.getGroupId())&&!"1".equals(materialUpload.getTypeId())){
					List<MaterialUpload> listTemp =new ArrayList<>();
					listTemp.add(materialUpload);
					mapTemp.put(materialUpload.getGroupId(),listTemp);
				}else if(!"1".equals(materialUpload.getTypeId())){
					mapTemp.get(materialUpload.getGroupId()).add(materialUpload);
				}
			}
			//根据已上传的客户资料反查资料类型
			Map<MaterialType,List<MaterialUpload>> ret=new LinkedHashMap<>();
			for (List<MaterialUpload> materialUploads : mapTemp.values()) {
				String typeId = materialUploads.get(0).getTypeId();
				//获取资料类型
				MaterialType materialType = materialTypeService.get(typeId);
				MaterialType materialTypeParent= materialTypeService.get(materialType.getParentId());
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialTypeParent);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues(dictService.findList(dict));
					}
				}
				materialTypeParent.setChildren(children);
				ret.put(materialTypeParent,materialUploads);
			}
			//查询所有资料类型
			MaterialType query2=new MaterialType();
			query2.setParent(new MaterialType("0"));
			List<MaterialType> list1 = materialTypeService.findList(query2);
			for (MaterialType materialType : list1) {
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialType);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues(dictService.findList(dict));
					}
				}
				materialType.setChildren(children);
			}
			model.addAttribute("typeList",list1);
			model.addAttribute("ret",ret);
		}
		//渠道银行
		model.addAttribute("banks",bankService.findList(new Bank()));

		return "modules/sys/loan/load/viewMemberInfoPage";
	}
	@RequiresPermissions("sys:member:member:bankcardmanager")
	@RequestMapping(value = "bankcardList")
	public String bankcardList(Member member, Model model) {
		MemberBankcard mb=new MemberBankcard();
		//查询出用户已绑定的银行卡
		mb.setMemberId(member.getId());
		model.addAttribute("mbList", memberBankcardService.findList(mb));
		model.addAttribute("member", member);
		return "modules/sys/member/memberBankcardListPage";
	}

	@RequiresPermissions("sys:member:member:edit")
	@RequestMapping(value = "save")
	public String save(Member member, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception {
		if (!beanValidator(model, member)){
			return form(member, model);
		}
//		if (member.getId()==null ||member.getId().trim().equals("")){
//			String tel = memberService.findtel1(member.getUsername());
//			if (tel !=null){
//				model.addAttribute("error","账户已存在");
//				return form(member,model);
//			}
//		}
		if(StringUtils.isBlank(member.getBalance())){
			member.setBalance("0");
		}
        String birthday = member.getBirthday();
        if(StringUtils.isNotBlank(birthday)){
            //时间存毫秒值
            Date date = DateUtil.StringToDate(birthday, "yyyy-MM-dd");
            member.setBirthday(date.getTime()+"");
        }
		if(StringUtils.isNotBlank(member.getEntryTime())){
			//时间存毫秒值
			Date date = DateUtil.StringToDate(member.getEntryTime(), "yyyy-MM-dd");
			member.setEntryTime(date.getTime()+"");
		}
		//避免插入空字符串

		member.setTelephone(member.getUsername());
        String telephone = member.getTelephone();
        if(StringUtils.isBlank(telephone)){
            member.setTelephone(null);
        }
        member.setCreateIp(IPUtils.getIpAddr(request));
		if(StringUtils.isBlank(member.getId())){
			//设置环信用户名和密码
			try {
				member.setHxUsername(UUIDUtils.getUUID() );
				member.setHxPassword(MD5Utils.md5Encode(member.getHxUsername()));
			}catch (Exception e){
				logger.error(e.getMessage());
			}
		}
		boolean isNew=false;
		if(StringUtils.isBlank(member.getId())){
            member.setPassword(MD5Utils.getMd5Password(member.getPassword(),member.getPassword()));
			isNew=true;
		}
		String mb1 = member.getManagerId();
		Member member1 = new Member();
		member1.setId(member.getId());
		String ms = member1.getId();
		String sd = memberService.findbusiness2(ms);
		if(!(mb1.equals(sd))) {
			TBusinessRecord businessRecord = new TBusinessRecord();
			member1.setCreateBy(member.getCreateBy());
			businessRecord.setMember(member1);
			businessRecord.setCreateBy(member.getCreateBy());
			if(sd!=null) {
				businessRecord.setRecord("该客户商务人员由【" + memberService.findbusiness1(member) + "】变更为【" + memberService.findbusiness(member.getManagerId()) + "】");
				businessRecordService.save(businessRecord);
				//(环信)删除原来商务人员和客户的朋友关系，修改的商务人员和客户建立朋友关系
				Member member2 = memberService.get(member.getId());
				String as =member2.getManagerId();
				User user = userService.get(as);
				imService.deleteFriendSingle(member.getHxUsername(),user.getHxUsername());
				User user1 = userService.get(mb1);
				imService.addFriendSingle(member.getHxUsername(),user1.getHxUsername());
				//删除t_friend中的旧关系，建立新朋友关系
				Friends friends = new Friends();
				friends.setFriendAId(member.getId());
				friends.setFriendBId(member2.getManagerId());
				Friends friends2 = friendsService.getIds(friends);
				friendsService.delete(friends2);
				Friends friends1 = new Friends();
				friends1.setFriendAId(member.getId());
				friends1.setFriendAType("1");
				friends1.setFriendBId(mb1);
				friends1.setFriendBType("0");
				friendsService.save(friends1);
			}
		}
			memberService.save(member);
		if(isNew){
			imService.createNewIMUserSingle(member.getHxUsername(),member.getHxPassword(),member.getTelephone());
			TBusinessRecord businessRecord1 = new TBusinessRecord();
			businessRecord1.setMember(memberService.get(member.getId()));
			businessRecord1.setCreateBy(member.getCreateBy());
			businessRecord1.setRecord("该客户商务人员新增为【"+memberService.findbusiness(member.getManagerId())+"】");
			businessRecordService.save(businessRecord1);
			//（环信）新增的客户和商务人员互相添加好友
			User user =userService.get(member.getManagerId());
			imService.addFriendSingle(member.getHxUsername(),user.getHxUsername());
			//添加朋友记录到t_friends
			Friends friends = new Friends();
			friends.setFriendAId(member.getId());
			friends.setFriendAType("1");
			friends.setFriendBId(member.getManagerId());
			friends.setFriendBType("0");
			friendsService.save(friends);
		}


		addMessage(redirectAttributes, "保存用户信息成功");

		return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
	}
	
	@RequiresPermissions("sys:member:member:edit")
	@RequestMapping(value = "delete")
	public String delete(Member member, RedirectAttributes redirectAttributes) {
		memberService.delete(member);
		addMessage(redirectAttributes, "删除用户信息成功");
		return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
	}

	/**
	 * 服务记录查看
	 * @param member 客户id
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:member:member:sr:view")
	@RequestMapping(value = "seviceRecordPage")
	public String seviceRecordPage(Member member, Model model) {
		ServiceRecord serviceRecord=new ServiceRecord();
		serviceRecord.setMember(member);
		List<ServiceRecord> srList = serviceRecordService.findList(serviceRecord);
		model.addAttribute("srList", srList);
		model.addAttribute("member", member);
		return "modules/sys/member/servicerecord";
	}
	/**
	 * 商务人员谈单记录查看
	 * @param member 客户id
	 * @param model
	 * @return
	 */
    @RequiresPermissions("sys:businessrecord:tBusinessRecord:view")
	@RequestMapping(value = "businessRecordPage")
	public String businessRecordPage(Member member, Model model) {
		TBusinessRecord businessRecord=new TBusinessRecord();
		businessRecord.setMember(member);
		List<TBusinessRecord> srList = businessRecordService.findList(businessRecord);
		model.addAttribute("srList", srList);
		model.addAttribute("member", member);
		return "modules/sys/businessrecord/businessRecord";
	}
	
	
	@RequestMapping(value = "/getMemberByHxUsername")
	@ResponseBody
	public Object getMemberByHxUsername(String hxUsername ,HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		Member m = memberService.getByHxUsername(hxUsername);
		if(m==null){
			User user=new User();
			user.setHxUsername(hxUsername);
			return systemService.getByHxUsername(user);
		}else{
			return m;
		}
	}

	@RequiresPermissions("sys:member:member:uploadmaterial")
	@RequestMapping(value = "uploadPage")
	public String uploadPage(Member member, Model model) {
		model.addAttribute("member", member);
		MaterialType query=new MaterialType();
		query.setParent(new MaterialType("0"));
		model.addAttribute("types", 	materialTypeService.findList(query));
		return "modules/sys/member/uploadPage";
	}

	@RequiresPermissions("sys:member:member:inputapply")
	@RequestMapping(value = "inputApplyPage")
	public String inputApplyPage(Member member, Model model) {
		model.addAttribute("member",member);
		String memberId=member.getId();
		//查询用户上传的资料
		if(StringUtils.isNotBlank(memberId)/*&&StringUtils.isNotBlank(materialTypeId)*/){
			MaterialUpload query=new MaterialUpload();
			//    query.setTypeId(materialTypeId);
			query.setMemberId(memberId);
			List<MaterialUpload> list = materialUploadService.findList(query);
			Map<String,List<MaterialUpload>> mapTemp=new HashMap<>();
			//给上传资料分组
			for (MaterialUpload materialUpload : list) {
				if(!mapTemp.containsKey(materialUpload.getGroupId())&&!"1".equals(materialUpload.getTypeId())){
					List<MaterialUpload> listTemp =new ArrayList<>();
					listTemp.add(materialUpload);
					mapTemp.put(materialUpload.getGroupId(),listTemp);
				}else if(!"1".equals(materialUpload.getTypeId())){
					mapTemp.get(materialUpload.getGroupId()).add(materialUpload);
				}
			}
			//根据已上传的客户资料反查资料类型
			Map<MaterialType,List<MaterialUpload>> ret=new LinkedHashMap<>();
			for (List<MaterialUpload> materialUploads : mapTemp.values()) {
				String typeId = materialUploads.get(0).getTypeId();
				//获取资料类型
				MaterialType materialType = materialTypeService.get(typeId);
				MaterialType materialTypeParent= materialTypeService.get(materialType.getParentId());
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialTypeParent);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues(dictService.findList(dict));
					}
				}
				materialTypeParent.setChildren(children);
				ret.put(materialTypeParent,materialUploads);
			}
			//查询所有资料类型
			MaterialType query2=new MaterialType();
			query2.setParent(new MaterialType("0"));
			List<MaterialType> list1 = materialTypeService.findList(query2);
			for (MaterialType materialType : list1) {
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialType);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues(dictService.findList(dict));
					}
				}
				materialType.setChildren(children);
			}
			model.addAttribute("typeList",list1);
			model.addAttribute("ret",ret);
		}
		//渠道银行
        model.addAttribute("banks",bankService.findList(new Bank()));
		return "modules/sys/member/inputApply";
	}

    @RequestMapping(value = "/getLoanByBankId")
    @ResponseBody
    public Object getLoanByBankId(String bankId )  {
        Loan loan=new Loan();
        loan.setBankId(bankId);
        return loanService.findList(loan);
    }

	@RequiresPermissions("sys:member:member:applymaterial")
	@RequestMapping(value = "checkFormPage")
	public String checkFormPage(Member member, Model model) {
		String memberId = member.getId();
		MaterialUpload materialUpload=new MaterialUpload();
		materialUpload.setMemberId(memberId);
		List<MaterialUpload> findList = materialUploadService.findList(materialUpload);
		List<MaterialUpload> validList =new ArrayList<>();
		for (MaterialUpload upload : findList) {
			if(!upload.getTypeId().equals("1")){
				validList.add(upload);
			}
		}
		model.addAttribute("muList", validList);
		member = memberService.get(member.getId());
		model.addAttribute("member", member);
		return "modules/sys/material/checkFormPage";
	}
	@RequiresPermissions("sys:loan:loanType:view")
	@RequestMapping(value = {"loanTypeList"})
	public String loanTypeList(LoanType loanType, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<LoanType> list = loanTypeService.findList(loanType);
		model.addAttribute("list", list);
		return "modules/sys/member/load/loanTypeList";
	}
	@RequiresPermissions("sys:loan:loan:view")
	@RequestMapping(value = {"loanList"})
	public String loanList(Loan loan, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Loan> p = new Page<>(request, response);
        p.setPageSize(10);
        Page<Loan> page = loanService.findPage(p, loan);
        List<Loan> list = page.getList();
        for (Loan loan1 : list) {
            String id = loan1.getId();
            LoanMaterialtypeRe loanMaterialtypeRe=new LoanMaterialtypeRe();
            loanMaterialtypeRe.setLoanId(id);
            List<LoanMaterialtypeRe> list1 = loanMaterialtypeReService.findList(loanMaterialtypeRe);
            if(!CollectionUtils.isEmpty(list1)){
                for (LoanMaterialtypeRe materialtypeRe : list1) {
                    String materialTypeId = materialtypeRe.getMaterialTypeId();
                    MaterialType type=new MaterialType(materialTypeId);
                    loan1.getMaterialTypes().add(materialTypeService.get(type));
                }
            }
        }
        model.addAttribute("page", page);
		return "modules/sys/member/load/loanList";
	}

	@RequiresPermissions("sys:member:member:edit")
	@RequestMapping(value = "load/userList")
	public String loadUserList(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<User> userPage = new Page<>(request, response);
        userPage.setPageSize(10);
        Page<User> page = systemService.findUser(userPage, user);
		model.addAttribute("page", page);
        return "modules/sys/member/load/userList";
	}

	@RequestMapping(value = {"downLoadMaterials"})
    @RequiresPermissions("sys:member:member:downloadmaterial")
	public String downLoadMatrials(String view, String id, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		Map<String,Object> data=new HashMap<>();
		if(StringUtils.isNotBlank(id)){
			MaterialUpload query=new MaterialUpload();
			//    query.setTypeId(materialTypeId);
			query.setMemberId(id);

			List<MaterialUpload> list = materialUploadService.findList(query);
			Map<String,List<MaterialUpload>> mapTemp=new HashMap<>();
			//给上传资料分组
			for (MaterialUpload materialUpload : list) {
				if(!mapTemp.containsKey(materialUpload.getGroupId())&&!"1".equals(materialUpload.getTypeId())){
					List<MaterialUpload> listTemp =new ArrayList<>();
					listTemp.add(materialUpload);
					mapTemp.put(materialUpload.getGroupId(),listTemp);
				}else if(!"1".equals(materialUpload.getTypeId())){
					mapTemp.get(materialUpload.getGroupId()).add(materialUpload);
				}
			}
			//根据已上传的客户资料反查资料类型
			Map<MaterialType,List<MaterialUpload>> ret=new LinkedHashMap<>();
			for (List<MaterialUpload> materialUploads : mapTemp.values()) {
				String typeId = materialUploads.get(0).getTypeId();
				//获取资料类型
				MaterialType materialType = materialTypeService.get(typeId);
				MaterialType materialTypeParent= materialTypeService.get(materialType.getParentId());
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialTypeParent);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues( dictservice.findList(dict));
					}
				}
				materialTypeParent.setChildren(children);
				ret.put(materialTypeParent,materialUploads);
			}
			//查询所有资料类型
			MaterialType query2=new MaterialType();
			query2.setParent(new MaterialType("0"));
			List<MaterialType> list1 = materialTypeService.findList(query2);
			for (MaterialType materialType : list1) {
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialType);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues( dictservice.findList(dict));
					}
				}
				materialType.setChildren(children);
			}
			MemberMaterial mm=new MemberMaterial();
            Member member = memberService.get(new Member(id));
            mm.setBaseInfo(memberService.get(new Member(id)));
            List<MaterialUpload> imgs=new ArrayList<>();
			for (Map.Entry<MaterialType,List<MaterialUpload>> entry : ret.entrySet()) {
                MaterialType key = entry.getKey();
                List<MaterialUpload> value = entry.getValue();
				MemberMaterialUpload mmu=new MemberMaterialUpload();
				mm.getItems().add(mmu);
				mmu.setTitle(key.getName());
                List<MaterialType> children = key.getChildren();
                List<MaterialUpload> mus =new ArrayList<>();
                for (MaterialType child : children) {
                    for (MaterialUpload materialUpload : value) {
                            if(materialUpload.getTypeId().equals(child.getId())){
								materialUpload.setTypeName(child.getName());
                                materialUpload.setTypeType(child.getType());
                                if("radiobox".equals(child.getType())){
                                    List<Dict> keyValues = child.getKeyValues();
                                    for (Dict keyValue : keyValues) {
                                        if(keyValue.getValue().equals(materialUpload.getValue())){
                                            materialUpload.setValue(keyValue.getLabel());
                                        }
                                    }
                                }
                                mus.add(materialUpload);
                            }
                    }
                }

                List<MaterialUpload> musSorted=new ArrayList<>();
                for (MaterialUpload mu : mus) {
                    if(!"fileselect".equals(mu.getTypeType())){
                        musSorted.add(mu);
                    }
                }

                //两个一组
                List<List<MaterialUpload>> lists = CollectionGroupUtils.groupMaterialUploadListByQuantity(musSorted, 2);

                for (MaterialUpload mu : mus) {
                    if("fileselect".equals(mu.getTypeType())){
                        List<MaterialUpload> materialUploads = new ArrayList<>();
                        mu.setValue(getImageStr(mu.getUrl()));
						materialUploads.add(mu);
                        imgs.add(mu);
                        lists.add(materialUploads);
                    }
                }
                mmu.setMus(lists);
            }
            data.put("imgs",imgs);
			data.put("mm",mm);
			try {
                StringBuilder userTitle=new StringBuilder();
                String username = member.getUsername();
                String realname = member.getRealname();
                String nickname = member.getNickname();
                userTitle.append(username);
				String name=username;
                if(StringUtils.isNotBlank(realname)){
					name=realname;
                    userTitle.append("("+realname+")");
                }else if(StringUtils.isNotBlank(nickname)){
					name=nickname;
                    userTitle.append("("+nickname+")");
                }
				mm.getBaseInfo().setUsername(name);
                WordUtils.exportMillCertificateWord(request,response,data,userTitle.toString()+"的资料文档.doc");
                addMessage(redirectAttributes, "下载用户资料成功");
                return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
        addMessage(redirectAttributes, "下载用户资料失败");
        return "redirect:"+Global.getAdminPath()+"/sys/member/member/?repage";

	}

    public String getImageStr(String imgFile) {

        InputStream in = null;
        byte[] data = null;
        try {
            if(imgFile.startsWith("http")){          //获取在线图片
				URL url = new URL(imgFile);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5 * 1000);
                in = conn.getInputStream();
            }else{      //获取线下图片
                in = new FileInputStream(imgFile);
            }
        /*
　　　　　//使用此种方式在获取在线图片时下载word中图片可能显示不全，其原因就是网络通讯往往是间断性的，一串字节往往分几批进行发送。本地程序调用available()方法有时得到0，这可能是对方还没有响应，也可能是对方已经响 应了，但是数据还没有送达本地。对方发送了1000个字节给你，也许分成3批到达，这你就要调用3次available()方法才能将数据总数全部得到。
　　　　　int count = 0;
        while (count == 0) {
            count = in.available();
        }
        data = new byte[count];*/
            int c;
            ByteArrayOutputStream buff = new ByteArrayOutputStream();
            while((c = in.read()) >= 0){
                buff.write(c);
            }
            data = buff.toByteArray();
            buff.close();
            in.read(data);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        if(data!=null && data.length>0){
            return encoder.encode(data);
        }
        return null;
    }

	@RequiresPermissions("sys:member:member:view")
	@RequestMapping(value = "membermate")
	public String membermate(Member member,HttpServletRequest request, HttpServletResponse response,Model model){
		Page<Loan> page = memberService.membermate(new Page<Loan>(request, response),member);
		model.addAttribute("page",page);
		model.addAttribute("member",member);
		return "modules/sys/member/membermate";
	}

	@RequestMapping(value = "menu")
	public String menu(Member member, Model model){
		ServiceRecord serviceRecord=new ServiceRecord();
		serviceRecord.setMember(member);
		List<ServiceRecord> serviceRecords = serviceRecordService.findList(serviceRecord);
		TBusinessRecord businessRecord=new TBusinessRecord();
		businessRecord.setMember(member);
		List<TBusinessRecord> tBusinessRecords = businessRecordService.findList(businessRecord);
		if (serviceRecords !=null && serviceRecords.size() > 0)
		model.addAttribute("serviceRecords", serviceRecords);
		model.addAttribute("member", member);
		if (tBusinessRecords !=null && tBusinessRecords.size() > 0)
		model.addAttribute("tBusinessRecords",tBusinessRecords);
		return "modules/sys/menu/zmenu";
	}

	@RequestMapping(value = "Information")
	public String information(Model model,String id){
		List<Member> ms = memberService.information(id);
		model.addAttribute("ms",ms);
		return "modules/sys/member/information";
	}
//	@ResponseBody
//	@RequestMapping(value = "/findtel1")
//	public BaseQueryVo findtel(String meberphone){
//		String tel = memberService.findtel1(meberphone);
//		BaseQueryVo baseQueryVo = new BaseQueryVo();
//		baseQueryVo.setRetCode(0);
//		baseQueryVo.setRetMsg("数据合法");
//		if(tel == null){
//			return baseQueryVo;
//		}
//		baseQueryVo.setRetCode(-1);
//		baseQueryVo.setRetMsg("该账户已存在");
//		return baseQueryVo;
//
//	}
	@RequestMapping(value = "getManage")
	public String getManage(Model model,String managerid){
		String sd = managerid;
        List<User> user = userService.finduser(sd);
		String num = "0";
		String clientnum = "0";
		String nownum = "0";
		String numweek = "0";
        if(memberService.checkbusiness(managerid).equals("1")){
        	num = memberService.servicenum(managerid);
        	clientnum = memberService.clientnums(managerid);
        	nownum = memberService.servicenummouth(managerid);
        	numweek = memberService.servicenumweek(managerid);
		}
		if(memberService.checkservice(managerid).equals("1")){
        	num = memberService.businessnum(managerid);
        	clientnum = memberService.clientnumb(managerid);
        	nownum = memberService.businessnummouth(managerid);
        	numweek = memberService.businessnumweek(managerid);
		}
		if(num == null){num="0";}if(nownum == null){nownum="0";}if(numweek == null){numweek="0";}
		String nowtime = memberService.getnowtime();
		model.addAttribute("user",user);
		model.addAttribute("clientnum",clientnum);
        model.addAttribute("num",num);
        model.addAttribute("nowtime",nowtime);
        model.addAttribute("weekstart",memberService.getweekstart());
		model.addAttribute("weekend",memberService.getweekend());
        model.addAttribute("nownum",nownum);
        model.addAttribute("week",numweek);
		return "modules/sys/member/getManage";
	}
//	@RequestMapping(value = "getMaps")
//	@ResponseBody
//	public Object getMaps(String id){
//		String ids = id;
//		List<Map<String,Object>> map = new  ArrayList<Map<String,Object>>();
//
//
//		if(memberService.checkbusiness(ids).equals("1")) {
//			map = memberService.servicemap(ids);
//		}
//		if(memberService.checkservice(ids).equals("1")){
//			map = memberService.businessmap(ids);
//		}
////		for(Map<String,Object> s : map) {
////			System.out.println(s.get("times"));
////		}
//		String st = memberService.getweekstart();
//		String ed = memberService.getweekend();
//		Calendar start = Calendar.getInstance();
//		start.set(Integer.parseInt(st.substring(0,4)), (Integer.parseInt(st.substring(5,7))-1), Integer.parseInt(st.substring(8,10)));
//		Long startTIme = start.getTimeInMillis();
//
//		Calendar end = Calendar.getInstance();
//		end.set(Integer.parseInt(ed.substring(0,4)), (Integer.parseInt(ed.substring(5,7))-1), Integer.parseInt(ed.substring(8,10)));
//		Long endTime = end.getTimeInMillis();
//
//		Long oneDay = 1000 * 60 * 60 * 24l;
//		List<Map<String,Object>> map2 = new  ArrayList<Map<String,Object>>();
//		Long time = startTIme;
//		while (time <= endTime) {
//			Date d = new Date(time);
//			Map map1  = new HashMap<String, Object>();
//			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//			time += oneDay;
////				for (Map<String, Object> m : map) {
////
////					String ms = m.get("times").toString();
////					String dc = df.format(d);
////					if (!ms.equals(dc)) {
////						map1.put("times", df.format(d));
////						map1.put("sum", 0);
////						map.add(map1);
////						map1 = new HashMap<String, Object>();
////					}
////				}
//			map1.put(df.format(d),0);
////			map1.put("sum", 0);
//			map2.add(map1);
//		}
//		List<Map<String,Object>> tmpMap = new ArrayList<>(map2);
////
////		for(Map<String,Object> b : map){
////				String bd = b.get("times").toString();
////			    String sums = b.get("sum").toString();
////				if(bd.equals()){
////					Map map3 = new HashMap();
////					map3.put(bd,sums);
////
////					tmpMap.add(map3);
////				}
////
////		}
//		return tmpMap;
//	}

	@RequestMapping(value = "getMaps")
	@ResponseBody
	public Object getMaps(String id){
		List<Map<String,Object>> map = new  ArrayList<Map<String,Object>>();
		if(memberService.checkbusiness(id).equals("1")) {
			map = memberService.servicemap(id);
		}
		if(memberService.checkservice(id).equals("1")){
			map = memberService.businessmap(id);
		}
		Map<String,String> weekMap = getWeekStartDate();
		if(map.size()>0 || map != null){
			for (Map<String,Object> item:map){
				weekMap.put(item.get("times").toString(), item.get("sum").toString());
			}
		}
		return weekMap;
	}
	public Map getWeekStartDate(){
		Map<String,String> sum = new HashMap<>();
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
		sum.put(s.format(cal.getTime()),"0");
		for (int  i = 0;i < 6;i++){
			cal.add( Calendar.DATE,1 );
			sum.put(s.format(cal.getTime()),"0");
		}
		return sum;
	}
	@RequestMapping(value = "getRemakes")
	public String getRemakes(String id,Model model){
		String ids =id;
		Member member =memberService.get(id);
		model.addAttribute("member",member);
		return "modules/sys/member/getRemakes";
	}
    @RequestMapping(value = "saveRemarks")
	@ResponseBody
	public Object saveRemarks(Member member){
		if(member != null) {
			memberService.save(member);
			return true;
		}
		else {
		return false;
		}
	}
}